// location.js
// import QQMapWX from 'qqmap-wx-jssdk';

class LocationService {
  constructor() {
    // this.qqmapsdk = new QQMapWX({
    //   key: '7JDBZ-UODE3-RSU3Z-RQIVC-2ZOYE-SHB6X'
    // });
    this.isRealTimeLocating = false;
    this.currentLocation = {
      longitude: null,
      latitude: null,
      address: null
    };
    this.locationChangeCallbacks = [];
  }

  // 检查并请求定位权限
  async checkLocationPermission() {
    return new Promise((resolve, reject) => {
      uni.getSetting({
        success(res) {
          if (!res.authSetting['scope.userLocation']) {
            uni.authorize({
              scope: 'scope.userLocation',
              success() {
                resolve(true);
              },
              fail() {
                uni.showModal({
                  title: '提示',
                  content: '若点击不授权，将无法使用位置功能',
                  cancelText: '不授权',
                  confirmText: '授权',
                  success(res) {
                    if (res.confirm) {
                      uni.openSetting();
                    }
                    reject(new Error('用户拒绝授权'));
                  }
                });
              }
            });
          } else {
            resolve(true);
          }
        },
        fail: reject
      });
    });
  }

  // 获取当前位置
  async getCurrentLocation() {
    try {
      await this.checkLocationPermission();
      
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'wgs84',
          success: async (res) => {
            this.currentLocation.longitude = res.longitude;
            this.currentLocation.latitude = res.latitude;
            
            // 获取地址信息
            try {
              const address = await this.reverseGeocode(res.longitude, res.latitude);
              this.currentLocation.address = address;
              resolve({...this.currentLocation});
            } catch (error) {
              reject(error);
            }
          },
          fail: (error) => {
            reject(error);
          }
        });
      });
    } catch (error) {
      throw error;
    }
  }

  // 逆地理编码
  // async reverseGeocode(longitude, latitude) {
  //   return new Promise((resolve, reject) => {
  //     this.qqmapsdk.reverseGeocoder({
  //       location: {
  //         latitude: latitude,
  //         longitude: longitude
  //       },
  //       success: (res) => {
  //         resolve(res.result.address || '未知地址');
  //       },
  //       fail: (res) => {
  //         reject(new Error('逆地理编码失败'));
  //       }
  //     });
  //   });
  // }

  // 开始实时定位
    async startRealTimeLocation(callback) {
      try {
        await this.checkLocationPermission();
        
        if (this.isRealTimeLocating) {
          return;
        }
  
        if (callback && typeof callback === 'function') {
          this.locationChangeCallbacks.push(callback);
        }
  
        wx.startLocationUpdate({
          success: () => {
            this.isRealTimeLocating = true;
            
            wx.onLocationChange((res) => {
              this.currentLocation.longitude = res.longitude;
              this.currentLocation.latitude = res.latitude;
              
              // 通知所有回调
              this.locationChangeCallbacks.forEach(cb => {
                cb({
                  longitude: res.longitude,
                  latitude: res.latitude
                });
              });
            });
          },
          fail: (err) => {
            throw new Error('开启实时定位失败');
          }
        });
      } catch (error) {
        throw error;
      }
    }

  // 停止实时定位
  stopRealTimeLocation() {
    if (!this.isRealTimeLocating) {
      return;
    }

    wx.stopLocationUpdate({
      success: () => {
        this.isRealTimeLocating = false;
        this.locationChangeCallbacks = [];
      },
      fail: (err) => {
        throw new Error('停止实时定位失败');
      }
    });
  }

  // 注册位置变化回调
  onLocationChange(callback) {
    if (typeof callback === 'function') {
      this.locationChangeCallbacks.push(callback);
    }
  }
}

// 导出单例
export const locationService = new LocationService();